package logger

import (
	"github.com/sirupsen/logrus"
	"gopkg.in/ini.v1"
	"io"
	"logger/fixopt"
	"logger/hooks"
	"os"
)

type option struct {
	Level  string `ini:"level"`
	Stdout bool   `ini:"stdout"`
	Format string `ini:"format"`
}

func (self *option) Ini(x *ini.File) error {
	return x.Section("log").MapTo(self)
}

var formatter = map[string]logrus.Formatter{
	"json": new(logrus.JSONFormatter),
	"text": new(logrus.TextFormatter),
}

func NewLogger(opts ...*fixopt.Field) (log *logrus.Logger, err error) {
	config := new(option)
	if err = fixopt.FixOptions(config, opts...); err != nil {
		return nil, err
	}

	if config.Format == "" {
		config.Format = "text"
	}

	chkout := func(c *option) io.Writer {
		if c.Stdout {
			return os.Stdout
		}
		return nil
	}

	var zdyhk logrus.LevelHooks
	zdyhk, err = hooks.WithHooks(opts...)
	if err != nil {
		return nil, err
	}

	if level, err := logrus.ParseLevel(config.Level); err != nil {
		return nil, err
	} else {
		return &logrus.Logger{
			Level:        level,
			Hooks:        zdyhk,
			ReportCaller: false,

			Out:       chkout(config),
			Formatter: formatter[config.Format],
		}, nil
	}
}
